<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="成员名称" prop="memberName">
        <el-input
          v-model="queryParams.memberName"
          placeholder="请输入成员名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> 
      <!-- <el-form-item label="用户名称" prop="userName">
        <el-select v-model="queryParams.userId" placeholder="请选择用户名称" clearable>
          <el-option
            v-for="item in userOptions"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item> -->
      

      <!-- <el-form-item label="团队ID" prop="teamId">
        <el-input
          v-model="queryParams.teamId"
          placeholder="请输入团队ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      
      <el-form-item label="所属团队" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择所属团队" clearable>
          <el-option
            v-for="item in teamOptions"
            :key="item.teamId"
            :label="item.teamName"
            :value="item.teamId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="职位" prop="position">
        <el-select v-model="queryParams.position" placeholder="请选择职位" clearable>
          <el-option
            v-for="item in postOptions"
            :key="item.postId"
            :label="item.postName"
            :value="item.postId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="加入日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeJoinDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="是否组长" prop="isLeader">
        <el-select v-model="queryParams.isLeader" placeholder="请选择是否组长" clearable>
          <el-option
            v-for="dict in sm_is_leader"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in sm_member_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['sm:member:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sm:member:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sm:member:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['sm:member:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="成员ID" align="center" prop="memberId" />
      <!-- <el-table-column label="用户名称" align="center" prop="userId" /> -->
      <el-table-column label="成员名称" align="center" prop="memberName" />
      <el-table-column label="团队" align="center" prop="teamName" />
      <el-table-column label="职位" align="center" prop="position"/>
       
      <el-table-column label="加入日期" align="center" prop="joinDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.joinDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否组长" align="center" prop="isLeader">
        <template #default="scope">
          <dict-tag :options="sm_is_leader" :value="scope.row.isLeader"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sm_member_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['sm:member:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['sm:member:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改团队成员对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="memberRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="成员名称" prop="memberName">
              <el-input v-model="form.memberName" placeholder="请输入成员名称" style="width: 200px;"/>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="用户名称" prop="userId">
              <el-select v-model="form.userId" placeholder="请选择用户名称" clearable>
                <el-option
                  v-for="item in teamOptions"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="所属团队" prop="teamId">
              <el-select v-model="form.teamId" placeholder="请选择所属团队" clearable>
                <el-option
                  v-for="item in teamOptions"
                  :key="item.teamId"
                  :label="item.teamName"
                  :value="item.teamId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-select v-model="form.position" placeholder="请选择职位" clearable>
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="加入日期" prop="joinDate">
              <el-date-picker
                v-model="form.joinDate"
                type="date"
                placeholder="选择加入日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否组长" prop="isLeader">
              <el-select v-model="form.isLeader" placeholder="请选择是否组长" :disabled="disableLeaderSelect">
                <el-option
                  v-for="dict in sm_is_leader"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option
                  v-for="dict in sm_member_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Member">
import { listMember, getMember, delMember, addMember, updateMember, listUser, listTeam } from "@/api/sm/member";
// import { listTeam as teamListTeam } from "@/api/sm/team";
import { listPost } from "@/api/system/post";
// import { addUser } from "@/api/system/user";

// const userOptions = ref([]);
const teamOptions = ref([]);
const postOptions = ref([]);
const { proxy } = getCurrentInstance();
const { sm_member_status, sm_is_leader } = proxy.useDict('sm_member_status', 'sm_is_leader');

const memberList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeJoinDate = ref([]);
const disableLeaderSelect = ref(false);
const currentMemberId = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // userId: null,
    teamId: null,
    position: null,
    joinDate: null,
    isLeader: null,
    status: null,
    memberName: null,
  },
  rules: {
    teamId: [
      { required: true, message: "所属团队不能为空", trigger: "change" }
    ],
    position: [
      { required: true, message: "职位不能为空", trigger: "change" }
    ],
    joinDate: [
      { required: true, message: "加入日期不能为空", trigger: "change" }
    ],
    isLeader: [
      { required: true, message: "是否组长不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询团队成员列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeJoinDate && '' != daterangeJoinDate) {
    queryParams.value.params["beginJoinDate"] = daterangeJoinDate.value[0];
    queryParams.value.params["endJoinDate"] = daterangeJoinDate.value[1];
  }
  listMember(queryParams.value).then(response => {
    memberList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeJoinDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.memberId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 检查团队是否已有组长 */
function checkTeamLeader(teamId, excludeMemberId = null) {
  if (!teamId) return;
  
  const params = {
    teamId: teamId,
    isLeader: "0" // 0表示是组长
  };
  
  return new Promise((resolve) => {
    listMember(params).then(response => {
      const leaders = response.rows || [];
      // 过滤掉当前编辑的成员（如果有）
      const filteredLeaders = leaders.filter(leader => leader.memberId !== excludeMemberId);
      
      if (filteredLeaders.length > 0) {
        // 团队已有其他组长
        disableLeaderSelect.value = true;
        // 如果是新增或者当前成员不是组长，默认设置为非组长
        if (!form.value.memberId || form.value.isLeader !== "0") {
          form.value.isLeader = "1"; // 1表示不是组长
        }
        resolve(true);
      } else {
        // 团队没有组长或者只有当前编辑的成员是组长
        disableLeaderSelect.value = false;
        resolve(false);
      }
    }).catch(() => {
      resolve(false);
    });
  });
}

/** 监听团队ID变化 */
watch(() => form.value.teamId, (newTeamId) => {
  if (newTeamId === 0) {
    // 当团队为未分配时，禁用组长选择并设置为否
    disableLeaderSelect.value = true;
    form.value.isLeader = "1"; // 1表示否
  } else {
    // 检查团队是否已有组长
    checkTeamLeader(newTeamId, form.value.memberId);
  }
});

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加团队成员";
  // 设置默认值
  form.value.teamId = 0; // 默认未分配团队
  form.value.isLeader = "1"; // 默认不是组长
  form.value.status = "0"; // 默认正常状态
  disableLeaderSelect.value = true; // 默认禁用组长选择
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _memberId = row.memberId || ids.value;
  currentMemberId.value = _memberId;
  
  getMember(_memberId).then(response => {
    form.value = response.data;
    
    // 检查团队ID，如果是未分配则禁用组长选择
    if (form.value.teamId === 0) {
      disableLeaderSelect.value = true;
      form.value.isLeader = "1";
    } else {
      // 检查团队是否已有组长
      checkTeamLeader(form.value.teamId, _memberId);
    }
    
    open.value = true;
    title.value = "修改团队成员";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["memberRef"].validate(valid => {
    if (valid) {
      if (form.value.memberId != null) {
        updateMember(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMember(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 表单重置 */
function reset() {
  form.value = {
    memberId: null,
    // userId: null,
    memberName: null,
    teamId: null,
    position: null,
    joinDate: null,
    isLeader: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("memberRef");
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _memberIds = row.memberId || ids.value;
  proxy.$modal.confirm('是否确认删除团队成员编号为"' + _memberIds + '"的数据项？').then(function() {
    return delMember(_memberIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sm/member/export', {
    ...queryParams.value
  }, `member_${new Date().getTime()}.xlsx`)
}

/** 处理组长选择变更 */
function handleLeaderChange(val) {
  if (val === '0') { // 0表示是组长
    proxy.$modal.msgSuccess('已设置为组长，保存后将自动更新团队负责人');
  }
}



// 在组件挂载时获取车间选项
onMounted(() => {
  // 获取用户列表
  // listUser().then(response => {
  //   userOptions.value = response.rows || response.data;
  // });
  // 获取团队列表
  listTeam().then(response => {
    teamOptions.value = response.rows || response.data;
  });
  // 获取岗位列表
  listPost().then(response => {
    postOptions.value = response.rows || response.data;
  });
  getList();
});
</script>
